<template>
  <div>
    <el-card class="box-card">
      <el-breadcrumb separator="/" style="margin-bottom: 20px">
        <el-breadcrumb-item :to="{ path: '/welcome/emp' }"
          >部门员工管理</el-breadcrumb-item
        >
        <el-breadcrumb-item>员工信息管理</el-breadcrumb-item>
      </el-breadcrumb>
      <template>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-input
              placeholder="请输入名称"
              clearable
              @change="search"
              v-model="params.usrName"
            >
              <i slot="prefix" class="el-input__icon el-icon-search"></i>
            </el-input>
          </el-col>
          <el-col :span="6">
            <el-button type="primary" @click="showAddDialog"
              ><i class="el-icon-plus"></i>添加</el-button
            >
          </el-col>
        </el-row>
      </template>
      <el-dialog
        title="添加"
        :close-on-click-modal="false"
        :visible.sync="addDialogVisible"
        :show-close="true"
      >
        <el-form :model="user" ref="user" :rules="rules">
          <el-form-item
            label="用户名"
            prop="usrName"
            :label-width="formLabelWidth"
          >
            <el-input v-model="user.usrName"></el-input>
          </el-form-item>
          <el-form-item
            label="密码"
            prop="usrPassword"
            :label-width="formLabelWidth"
          >
            <el-input v-model="user.usrPassword"></el-input>
          </el-form-item>

          <el-form-item label="角色" :label-width="formLabelWidth">
            <el-select v-model="roleId" placeholder="请选择">
              <el-option
                v-for="item in roles"
                :key="item.roleId"
                :label="item.roleName"
                :value="item.roleId"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="addUser('user')">保存</el-button>
        </div>
      </el-dialog>
      <el-dialog
        title="修改"
        :close-on-click-modal="false"
        :visible.sync="editDialogVisible"
        :show-close="true"
      >
        <el-form :model="user" ref="user" :rules="rules">
          <el-form-item
            label="员工姓名"
            prop="usrName"
            :label-width="formLabelWidth"
          >
            <el-input v-model="user.usrName"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="updateUser('user')">保存</el-button>
        </div>
      </el-dialog>
      <el-table border :data="tableData" style="width: 100%; margin-top: 20px">
        <el-table-column prop="usrId" label="员工编号"> </el-table-column>
        <el-table-column prop="usrName" label="员工姓名"> </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button size="mini" @click="editShowDialog(scope.row)"
              >编辑</el-button
            >
            <el-button
              size="mini"
              type="danger"
              @click="removeUserById(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <template>
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="params.pageIndex"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="params.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="params.total"
        >
        </el-pagination>
      </template>
    </el-card>
  </div>
</template>
<script>
export default {
  data() {
    return {
      tableData: [],
      params: {
        pageSize: 5, //每页显示5条记录
        pageIndex: 1, //当前第几页
        total: 0, //共几条记录去分页
        usrName: "",
      },
      did: 0,
      user: {
        usrName: "",
        usrPassword: "",
      },

      roles: [
      ],
      roleId: "",
      addDialogVisible: false,
      editDialogVisible: false,
      formLabelWidth: "120px",
      rules: {
        usrName: [
          { required: true, message: "请输入名称", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "长度在 3 到 10 个字符",
            trigger: "blur",
          },
        ],
        usrPassword: [{ required: true }],
      },
    };
  },
  //mounted:在模板渲染成html后调用，通常是初始化页面完成后，再对html的dom节点进行一些需要的操作
  mounted() {
    this.search();
  },
  methods: {
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.params.pageSize = val;
      this.search();
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.params.pageIndex = val;
      this.search();
    },
    async search() {
      const url = "/user/userList";
      const { data: res } = await this.$ajax
        .get(url, {
          params: {
            pageIndex: this.params.pageIndex,
            pageSize: this.params.pageSize,
            userName: this.params.usrName,
          },
          headers: {
            token: localStorage.getItem("token"),
          },
        })
        .catch((error) => {
          this.$message.error("发生异常,请重新登录");
          this.$router.push("/login");
        });
      if (res.errorCode == "-1") {
        this.$message.error("token不存在,请重新登录!");
        this.$router.push("/login");
      }
      console.log(res);
      this.tableData = res.data.records;
      this.params.total = res.data.total;
    },

    showAddDialog() {
      this.getRole();     
      this.addDialogVisible = true;
    },


    async getRole() {
      const url = "/user/getrolelist";
      const { data: res } = await this.$ajax
        .get(url, {
          params: {
          },
          headers: {
            token: localStorage.getItem("token"),
          },
        })
      this.roles=res.data;
    },


    addUser(user) {
      this.$refs[user].validate(async (valid) => {
        if (valid) {
          const url = "/user/add";
          const { data: res } = await this.$ajax.get(url, {
            params: {
              usrName: this.user.usrName,
              roleId: this.roleId,
              usrPassword: this.user.usrPassword,
            },
            headers: {
              token: localStorage.getItem("token"),
            },
          });
          console.log(res);
          if (res.success == "true") {
            this.$message({
              message: "添加成功",
              type: "success",
            });
            this.addDialogVisible = false;
            this.search();
            this.user = {
              usrName: "",
              usrPassword: "",
            };
          } else {
            this.$message.error("添加失败");
          }
        }
      });
    },
    //根据id删除
    async removeUserById(row) {
      const url = "/user/deletebyid";
      const { data: res } = await this.$ajax.get(url, {
        params: {
          id: row.usrId,
        },
        headers: {
          token: localStorage.getItem("token"),
        },
      });
      if (res.success == "true") {
        this.$message({
          message: "删除成功",
          type: "success",
        });
        this.search();
      } else {
        this.$message.error("删除失败");
      }
    },
    //根据id查看用户
    editShowDialog(row) {
      console.log(row);
      this.user.usrName = row.usrName;
      this.did = row.usrId;
      this.editDialogVisible = true;
    },
    //根据id修改用户
    async updateUser() {
      const url = "/user/update";
      const { data: res } = await this.$ajax.get(url, {
        params: {
          usrName: this.user.usrName,
          id: this.did,
        },
        headers: {
          token: localStorage.getItem("token"),
        },
      });
      if (res.success == "true") {
        this.$message({
          message: "修改成功",
          type: "success",
        });
        this.editDialogVisible = false;
        this.search();
        this.user = {
          usrName: "",
        };
        this.did = 0;
      } else {
        this.$message.error("修改失败");
      }
    },
  },
};
</script>
<style>
.breadcrumb {
  height: 30px;
}
</style>